<?php

class Curl {

    protected $ch;
    public $error;
    public $Cookies;
    public $Header;

    function __construct(){

        $this->ch = curl_init();    //创建cURL对象
        curl_setopt($this->ch, CURLOPT_HEADER, 1);    //是否输出头信息，0为不输出，非零则输出
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);    //设置输出方式, 0为自动输出返回的内容, 1为返回输出的内容,但不自动输出.
        curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, 5);    // 设置超时 30秒
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($this->ch, CURLOPT_ENCODING, "gzip");
    }

    public function post($_Get_Url,$_Form_Data){

        curl_setopt($this->ch, CURLOPT_URL, $_Get_Url);    //设置读取URL
        curl_setopt($this->ch, CURLOPT_POST, 1);    //设置为 POST 提交
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, $_Form_Data);    //设置POST数据
        return $this->exec();
    }

    public function get($_Get_Url){

        curl_setopt($this->ch, CURLOPT_URL, $_Get_Url);    //设置读取URL
        curl_setopt($this->ch, CURLOPT_POST, 0);    //设置为 POST 提交
        return $this->exec();
    }

    public function cookie($_Cookie){
        if(is_array($_Cookie)){
            $_Cookie = implode('',$_Cookie);
        }
        $_Cookie = substr($_Cookie,0,-1);
        curl_setopt($this->ch, CURLOPT_COOKIE, $_Cookie);    // 设置 Cookies
        return $this;
    }

    public function header($_Headers){

        if(isset($_Headers['User-Agent'])){
            curl_setopt($this->ch, CURLOPT_USERAGENT, $_Headers['User-Agent']);
        }
        curl_setopt($this->ch, CURLOPT_HTTPHEADER, $_Headers);    // 设置附加协议头
        return $this;
    }
    //获取响应头
    public function getInfo(){
        return curl_getinfo($this->ch);
    }


    protected function exec(){

        $html = curl_exec($this->ch);  //执行

        if ($html === False) {    //获取错误,
            $this->error = curl_error($this->ch);
            return false;
        }

        // 区分头信息与正文
        $_wz = strpos($html,"\r\n\r\n");
        $this->Header = substr($html,0,$_wz);    //截取头信息
        if($this->Header == "HTTP/1.1 100 Continue"){
            $html = substr($html,$_wz+4);
            $_wz = strpos($html, "\r\n\r\n");
            $this->Header = substr($html,0,$_wz);    //截取头信息
        }
        // 获取Cookies 信息
        if(preg_match_all("/set-cookie:\s?(.*?=.*?);/i", $this->Header, $cookie)){
            $cookie = $cookie[1];
        }
        foreach ($cookie as $value){

            if(!is_array($value)){
                $tmp = explode('=',$value);
                $this->Cookies[trim($tmp[0])] = $value."; ";
            }
        }

        $ret = substr($html,$_wz+4);    //获取正文
        return $ret;
    }
}